var WxParse = require('wxParse/wxParse.js');
var util = require('utils/util.js');
var request = require('utils/request.js');
App({
  onLaunch: function () {
  },
  getToken: function () {
    var that = this;
    // 获取本地存储中的token
    wx.getStorage({
      key: 'token',
      success: function (res) {//有该数据
        console.log(res.data)
        that.setData({
          token: res.data
        })
      },
      fail: function (res) {
        console.log(res.data)
        //调用授权方法-设置token
        app.getUserInfo();
      }
    })
  },

  //判断本地是否有token
  loginFlag: function () {
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function (res) {//有该数据
        console.log(res.data)
        console.log("本地存储中有token，未过期")
        // that.getUserInfo();
      },
      fail: function (res) {//没有该数据
        console.log(res.data)
        //调用授权方法-设置token
        that.getUserInfo();
      }
    })
  },
  getUserInfo: function () {
    var that = this;
    wx.login({
      success: function (res) {
        console.log(res);
        console.log("获取用户信息成功")
        if (res.code) {
          //发起网络请求
          request.login(
            {
              "code": res.code
            }, (res) => {
              console.log(res.data);
              var session_id = res.data.session_id;
              // that.globalData.session_id = res.data.session_id;
              //设置本地缓存
              wx.setStorage({
                key: "token",
                data: res.data.session_id,
                success: function () {
                  wx.getUserInfo({
                    success: function (res) {
                      console.log(res);
                      var iv = res.iv;
                      var encryptedData = res.encryptedData;
                      wx.setStorageSync("isOk","true")
                      //读取本地缓存
                      wx.getStorage({
                        key: 'token',
                        success: function (res) {
                          console.log(res.data)
                          request.checkLogin(
                            {
                              'iv': iv,
                              'encryptedData': encryptedData,
                              'session_id': res.data
                            }, (res) => {
                              console.log(res);
                            }
                          )
                        }
                      })
                    }
                  })

                }
              })
            }
          )
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail:function(res){
        console.log(res);
        console.log("获取用户信息失败")
      }
    });
  },
  globalData: {
    location:"    定位中..."
  }
})

